package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.exception.CommonException;
import com.xmy.cultivate.mapper.AppointSchoolMapper;
import com.xmy.cultivate.mapper.RoleAdminMapper;
import com.xmy.cultivate.mapper.StaffMapper;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.IdWorker;
import com.xmy.cultivate.util.ResultCode;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 员工 服务实现类
 * </p>
 *
 * @author min
 * @since 2022-07-26
 */
@Service
public class StaffServiceImpl extends ServiceImpl<StaffMapper, Staff> implements IStaffService {


    @Autowired
    IAdminService iAdminService;

    @Autowired
    IRoleAdminService iRoleAdminService;

    @Autowired
    IAppointSchoolService iAppointSchoolService;

    @Autowired
    AppointSchoolMapper appointSchoolMapper;

    @Autowired
    StaffMapper staffMapper;

    @Autowired
    RoleAdminMapper roleAdminMapper;

    @Autowired
    IRoleService iRoleService;

    @Autowired
    IdWorker idWorker;

    @Autowired
    IMqPushService iMqPushService;

    /**
     * 批量更新企业微信号
     */
    @Override
    public void batchUpdateQyWeChartId(){
        QueryWrapper<Staff> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("status",1,3);
        queryWrapper.isNull("qy_wechar_id");
        List<Staff> staffList = staffMapper.selectList(queryWrapper);
        for (Staff staff:staffList){
            if (StringUtils.isNotBlank(staff.getPhone())){
                if (staff.getPhone().length() == 11){
                    iMqPushService.updateQyWecharId(staff);
                }
            }
        }
    }

    @Transactional
    public boolean saveTo(Staff staff){
        Long adminId = idWorker.nextId();
        Admin admin = staff.getAdminObj();
        if(admin.getAccount() != null && admin.getAccount() != ""){
            String account = admin.getAccount();
            Long count = iAdminService.count(new QueryWrapper<Admin>().eq("account",account));
            if(count > 0){
                throw new CommonException(ResultCode.ACCOUNT_IN);
                //throw new CommonException(ResultCode.quarterNo);
            }

            admin.setId(adminId);

            String pwd = new Md5Hash(admin.getPwd(),admin.getAccount(),3).toString();
            admin.setPwd(pwd);
            iAdminService.save(admin);

            //机构账号，管辖校区
            List<AppointSchool> appointSchoolList = new ArrayList<>();
            for (Long item:admin.getSchoolIdList()){
                AppointSchool appointSchool = new AppointSchool();
                appointSchool.setForId(adminId);
                appointSchool.setSchoolId(item);
                appointSchool.setType(2);//机构帐号指定校区
                appointSchoolList.add(appointSchool);
            }
            //机构账号，角色
            List<RoleAdmin> roleAdminList = new ArrayList<>();
            for (Long item:admin.getRoleIdList()){
                RoleAdmin roleAdmin = new RoleAdmin();
                roleAdmin.setRoleId(item);
                roleAdmin.setAdminId(adminId);
                roleAdminList.add(roleAdmin);
            }

            if(appointSchoolList.size()>0){
                iAppointSchoolService.saveBatch(appointSchoolList,appointSchoolList.size());
            }
            if(roleAdminList.size()>0){
                iRoleAdminService.saveBatch(roleAdminList,roleAdminList.size());
            }
        }

        staff.setId(adminId);
        staff.setAdminId(adminId);

        //所属部门
        List<AppointSchool> departList = new ArrayList<>();
        //老师，上课校区范围
        List<AppointSchool> scopeSchoolList = new ArrayList<>();

        for(Long id:staff.getDepartIdList()){
            AppointSchool appointSchool = new AppointSchool();
            appointSchool.setSchoolId(id);
            appointSchool.setForId(staff.getId());
            appointSchool.setType(3);
            departList.add(appointSchool);
        }

        for (Long id:staff.getScopeSchoolIdList()){
            AppointSchool appointSchool = new AppointSchool();
            appointSchool.setSchoolId(id);
            appointSchool.setForId(staff.getId());
            appointSchool.setType(4);
            scopeSchoolList.add(appointSchool);
        }

        if(departList.size()>0){
            iAppointSchoolService.saveBatch(departList,departList.size());
        }
        if(scopeSchoolList.size()>0){
            iAppointSchoolService.saveBatch(scopeSchoolList,scopeSchoolList.size());
        }

        this.save(staff);

        return true;
    }

    @Transactional
    public boolean updateTo(Staff staff){
        Admin admin = staff.getAdminObj();
        Long adminId = staff.getId();

        if(admin.getId() != null){
            String account = admin.getAccount();
            Admin adminOld = iAdminService.getById(staff.getId());
            Long count = iAdminService.count(new QueryWrapper<Admin>().eq("account",account).ne("account",adminOld.getAccount()));

            if(count > 0){
                throw new CommonException(ResultCode.ACCOUNT_IN);
                //throw new CommonException(ResultCode.quarterNo);
            }

            admin.setId(staff.getId());
            if(StringUtils.isNotBlank(admin.getPwd())){
                String pwd = new Md5Hash(admin.getPwd(),admin.getAccount(),3).toString();
                admin.setPwd(pwd);
            }

            //iAdminService.updateById(admin);

            iAdminService.updateById(admin);
            //先删除指定校区
            QueryWrapper<AppointSchool> delAppointSchoolQueryWrapper = new QueryWrapper<>();
            delAppointSchoolQueryWrapper.eq("for_id",admin.getId()).eq("type",2);
            appointSchoolMapper.delete(delAppointSchoolQueryWrapper);
            List<AppointSchool> appointSchoolList = new ArrayList<>();
            for (Long item:admin.getSchoolIdList()){
                AppointSchool appointSchool = new AppointSchool();
                appointSchool.setForId(staff.getId());
                appointSchool.setSchoolId(item);
                appointSchool.setType(2);//机构帐号指定校区
                appointSchoolList.add(appointSchool);
            }
            //先删除角色
            QueryWrapper<RoleAdmin> roleAdminQueryWrapper = new QueryWrapper<>();
            roleAdminQueryWrapper.eq("admin_id",admin.getId());
            roleAdminMapper.delete(roleAdminQueryWrapper);
            List<RoleAdmin> roleAdminList = new ArrayList<>();
            for (Long item:admin.getRoleIdList()){
                RoleAdmin roleAdmin = new RoleAdmin();
                roleAdmin.setRoleId(item);
                roleAdmin.setAdminId(admin.getId());
                roleAdminList.add(roleAdmin);
            }
            if(appointSchoolList.size()>0){
                iAppointSchoolService.saveBatch(appointSchoolList,appointSchoolList.size());
            }
            if(roleAdminList.size()>0){
                iRoleAdminService.saveBatch(roleAdminList,roleAdminList.size());
            }
        }else {
            String account = admin.getAccount();
            Long count = iAdminService.count(new QueryWrapper<Admin>().eq("account",account));
            if(count > 0){
                throw new CommonException(ResultCode.ACCOUNT_IN);
                //throw new CommonException(ResultCode.quarterNo);
            }

            admin.setId(adminId);

            String pwd = new Md5Hash(admin.getPwd(),admin.getAccount(),3).toString();
            admin.setPwd(pwd);
            iAdminService.save(admin);

            //机构账号，管辖校区
            List<AppointSchool> appointSchoolList = new ArrayList<>();
            for (Long item:admin.getSchoolIdList()){
                AppointSchool appointSchool = new AppointSchool();
                appointSchool.setForId(adminId);
                appointSchool.setSchoolId(item);
                appointSchool.setType(2);//机构帐号指定校区
                appointSchoolList.add(appointSchool);
            }
            //机构账号，角色
            List<RoleAdmin> roleAdminList = new ArrayList<>();
            for (Long item:admin.getRoleIdList()){
                RoleAdmin roleAdmin = new RoleAdmin();
                roleAdmin.setRoleId(item);
                roleAdmin.setAdminId(adminId);
                roleAdminList.add(roleAdmin);
            }

            if(appointSchoolList.size()>0){
                iAppointSchoolService.saveBatch(appointSchoolList,appointSchoolList.size());
            }
            if(roleAdminList.size()>0){
                iRoleAdminService.saveBatch(roleAdminList,roleAdminList.size());
            }
        }

        //所属部门
        List<AppointSchool> departList = new ArrayList<>();
        //老师，上课校区范围
        List<AppointSchool> scopeSchoolList = new ArrayList<>();

        for(Long id:staff.getDepartIdList()){
            AppointSchool appointSchool = new AppointSchool();
            appointSchool.setSchoolId(id);
            appointSchool.setForId(staff.getId());
            appointSchool.setType(3);
            departList.add(appointSchool);
        }

        for (Long id:staff.getScopeSchoolIdList()){
            AppointSchool appointSchool = new AppointSchool();
            appointSchool.setSchoolId(id);
            appointSchool.setForId(staff.getId());
            appointSchool.setType(4);
            scopeSchoolList.add(appointSchool);
        }
        //先删除部门
        iAppointSchoolService.remove(new QueryWrapper<AppointSchool>().eq("for_id",staff.getId()).eq("type",3));
        if(departList.size()>0){
            iAppointSchoolService.saveBatch(departList,departList.size());
        }

        //先删除上课校区范围指定校区
        iAppointSchoolService.remove(new QueryWrapper<AppointSchool>().eq("for_id",staff.getId()).eq("type",4));
        if(scopeSchoolList.size()>0){
            iAppointSchoolService.saveBatch(scopeSchoolList,scopeSchoolList.size());
        }
        //staff.setId(adminId);
        this.updateById(staff);
        return true;
    }

    public Staff findOneById(Long id){
        Staff staff = staffMapper.findOneById(id);

        List<Long> departIdList = appointSchoolMapper.getSchoolIdListForForId(staff.getId(),3);
        List<Long> scopeSchoolIdList = appointSchoolMapper.getSchoolIdListForForId(staff.getId(),4);
        staff.setDepartIdList(departIdList);
        staff.setScopeSchoolIdList(scopeSchoolIdList);
        Admin admin = staff.getAdminObj();
        if(admin!=null){
            List<Long> schoolIdList = appointSchoolMapper.getSchoolIdListForForId(admin.getId(),2);
            List<Long> roleIdList = roleAdminMapper.getRoleIdListForAdminId(admin.getId());
            admin.setSchoolIdList(schoolIdList);
            admin.setRoleIdList(roleIdList);
        }
        return staff;
    }

    public IPage<Staff> findAll(IPage<?> page,Wrapper wrapper){

        IPage<Staff> staffIPage = staffMapper.findAll(page,wrapper);
        for (Staff staff:staffIPage.getRecords()){
            if(staff.getAdminObj() != null){
                Admin admin = staff.getAdminObj();
                List<Role> roleList = iRoleService.list(new QueryWrapper<Role>().inSql("id","select role_id from role_admin where admin_id="+admin.getId()));
                admin.setRoleList(roleList);
            }
        }

        return staffIPage;
    }
}
